package cn.melonlib.download.comp.service.impl;

import cn.melonlib.download.comp.service.DownloadService;
import cn.melonlib.download.comp.service.StreamResource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
@ConditionalOnProperty(value = "web.stream.download.type",havingValue = "simple",matchIfMissing = false)
public class SimpleDownloadService implements DownloadService {

    public void download(HttpServletRequest request, HttpServletResponse response,String name,Long size,String contentType, InputStream in) throws IOException {
        response.setHeader("Location", URLEncoder.encode(name, StandardCharsets.UTF_8));
        response.setHeader("Content-Disposition", "filename*=UTF-8''" + URLEncoder.encode(name, StandardCharsets.UTF_8));
        response.setContentLengthLong(size);
        response.setContentType(contentType);
        try(OutputStream out=response.getOutputStream()) {
            StreamUtils.copy(in,out);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
